import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/home/Home'
import Login from '../views/login/Login'
import Register from '../views/register/Register'

const routes = [
  // 访问根路径时，展示Home页面
  {
    path: '/',
    name: 'Home',
    component: () => import(/* webpackChunkName: "home" */ '../views/home/Home.vue') // 异步（动态）路由（只加载当前页面数据）
  },
  // 店铺详情页面
  {
    path: '/shop/:id', // :id表示访问shop路由时必须带数字（为了展示对应商家详情）
    name: 'Shop',
    component: () => import(/* webpackChunkName: "shop" */ '../views/shop/Shop.vue') // 异步路由
  },
  // 登陆页面
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login/Login.vue'), // 异步路由
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage // 登陆状态为本地存储中的登陆状态
      isLogin ? next({ name: 'Home' }) : next()
    }
  },
  // 注册页面
  {
    path: '/register',
    name: 'Register',
    component: () => import(/* webpackChunkName: "register" */ '../views/register/Register.vue'), // 异步路由
    beforeEnter (to, from, next) {
      const { isLogin } = localStorage // 登陆状态为本地存储中的登陆状态
      isLogin ? next({ name: 'Home' }) : next()
    }
  }
  // {
  //   path: '/about',
  //   name: 'About',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, from, next)=>{
  const isLogin = localStorage.isLogin;
  const { name } = to; //解构对象取值
  const isLoginOrRegister = (name === 'Login' || name === 'Register')
  if(isLogin || isLoginOrRegister){
    next();
  }else {
    next({name: 'Login'});
  }
})
export default router
